package com.zero.code;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class SignCode {
    private static String publicKey;
    private static String privateKey;
    private static String Algorithm = "RSA";

    public static void generatePairKey() throws NoSuchAlgorithmException {
        // RSA密钥对生成器
        KeyPairGenerator generator = KeyPairGenerator.getInstance(Algorithm);
        // 密钥长度，1024已被破解，建议2048
        generator.initialize(1024);
        // 生成一个密钥对
        KeyPair keyPair = generator.generateKeyPair();
        RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
        publicKey = new String(Base64.getEncoder().encode(rsaPublicKey.getEncoded()));
        System.out.println("公钥：" + publicKey);
        privateKey = new String(Base64.getEncoder().encode(rsaPrivateKey.getEncoded()));
        System.out.println("私钥：" + privateKey);
    }

    public static String sign(String source, String privateKeyStr) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, SignatureException {
        byte[] encode = Base64.getDecoder().decode(privateKeyStr);
        RSAPrivateKey privateKey = (RSAPrivateKey) KeyFactory.getInstance(Algorithm).generatePrivate(new PKCS8EncodedKeySpec(encode));
        // 获取一个签名实例
        Signature signature = Signature.getInstance(Algorithm);
        // 初始化
        signature.initSign(privateKey);
        signature.update(Base64.getDecoder().decode(source));
        // 签名
        byte[] result = signature.sign();
        return new String(Base64.getEncoder().encode(result));
    }

    public static boolean validSign(String source, String signData, String publicKeyStr) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {
        byte[] encode = Base64.getDecoder().decode(publicKeyStr);
        // 反向生成公钥
        RSAPublicKey publicKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(encode));
        // 获取一个验签名实例
        Signature signature = Signature.getInstance(Algorithm);
        // 初始化
        signature.initVerify(publicKey);
        signature.update(Base64.getDecoder().decode(source));
        return signature.verify(Base64.getDecoder().decode(signData));
    }

}
